import { delArticle, getArticleList, getChannelList } from '@/store/actions/article'
import { Card, Breadcrumb, Form, Button, Radio, Select, DatePicker, Table, Image, Tag, Space, message } from 'antd'
import { EditOutlined, DeleteOutlined, ExclamationCircleOutlined } from '@ant-design/icons'
import { useEffect, useRef } from 'react'
import { useSelector } from 'react-redux'
import { useDispatch } from 'react-redux'
import { Link, useHistory } from 'react-router-dom'
import styles from './index.module.scss'
import img from '@/assets/error.png'
import confirm from 'antd/lib/modal/confirm'

const { Option } = Select
const { RangePicker } = DatePicker
const STATUS = [
  { id: -1, title: '全部', color: 'magenta' },
  { id: 0, title: '草稿', color: 'red' },
  { id: 1, title: '待审核', color: 'volcano' },
  { id: 2, title: '审核通过', color: 'lime' },
  { id: 3, title: '审核失败', color: 'gold' }
]

export default function Article() {
  const dispatch = useDispatch()
  const histroy = useHistory()
  useEffect(() => {
    // dispath(某异步action)
    dispatch(getChannelList())
    dispatch(getArticleList())
  }, [dispatch])

  const channels = useSelector(state => state.article.channels)
  const artObj = useSelector(state => state.article.articles)
  const query = useRef({})

  // 处理筛选按钮的点击
  const handleFinish = (values) => {
    // 屏蔽掉 -1 的 status 情况
    if (values.status !== -1) { query.current.status = values.status }
    // 处理日期
    if (values.date) {
      query.current.begin_pubdate = values.date[0].startOf('day').format('YYYY-MM-DD HH:mm:ss')
      query.current.end_pubdate = values.date[1].endOf('day').format('YYYY-MM-DD HH:mm:ss')
    }
    // 处理频道的选择
    if (values.channel_id) { query.current.channel_id = values.channel_id }

    dispatch(getArticleList(query.current))
  }
  // 处理分布按钮的点击
  const handleChange = (page, pageSize) => {
    query.current.page = page
    query.current.per_page = pageSize

    dispatch(getArticleList(query.current))
  }

  // 处理删除
  const handleDel = async (id) => {
    confirm({
      title: '温馨提示',
      icon: <ExclamationCircleOutlined />,
      content: '你确认要删除这个文章么',
      async onOk() {
        await dispatch(delArticle(id))
        await dispatch(getArticleList(query.current))
        message.success('删除成功', 2)
      }
    })
  }

  const columns = [
    {
      title: '封面', dataIndex: 'cover', render: value => {
        if (value.type === 0) {
          return <Image width={200} height={150} src={img}></Image>
        } else {
          return (<Image width={200} height={150} src={value.images[0]} fallback={img} ></Image>)
        }
      }
    },
    { title: '标题', dataIndex: 'title' },
    {
      title: '状态', dataIndex: 'status', render: value => {
        const obj = STATUS.find(item => item.id === value)
        return obj ? <Tag color={obj.color}>{obj.title}</Tag> : <Tag color='gray'>未知</Tag>
      }
    },
    { title: '发布时间', dataIndex: 'pubdate' },
    { title: '阅读数', dataIndex: 'read_count' },
    { title: '评论数', dataIndex: 'comment_count' },
    { title: '点赞数', dataIndex: 'like_count' },
    {
      title: '操作', dataIndex: 'id', render(value) {
        return (<Space>
          <Button type='primary' shape='circle' icon={<EditOutlined />}></Button>
          <Button onClick={() => handleDel(value)} type='danger' shape='circle' icon={<DeleteOutlined />}></Button>
        </Space>)
      }
    }
  ]

  return (
    <div className={styles.root}>
      <Card title={
        <Breadcrumb>
          <Breadcrumb.Item><Link to="/home">首页</Link></Breadcrumb.Item>
          <Breadcrumb.Item>文章列表</Breadcrumb.Item></Breadcrumb>}>
        <Form initialValues={{ status: -1 }} onFinish={handleFinish}>
          <Form.Item label='状态' name='status'>
            <Radio.Group>
              {STATUS.map(item => (<Radio key={item.id} value={item.id}>{item.title}</Radio>))}
            </Radio.Group>
          </Form.Item>
          <Form.Item label='频道' name='channel_id'>
            <Select placeholder='请选择频道' style={{ width: 200 }}>
              {channels.map((item) => (<Option key={item.id} value={item.id}>{item.name}</Option>))}
            </Select>
          </Form.Item>
          <Form.Item label='日期' name='date'><RangePicker /></Form.Item>
          <Form.Item>
            <Button type='primary' htmlType='submit'>筛选</Button>
          </Form.Item>
        </Form>
      </Card>

      <Card title={`以下是筛选结果，总计 ${artObj.total_count} 条结果`} style={{ marginTop: 10 }}>
        <Table rowKey='id' dataSource={artObj.results} columns={columns} pagination={{
          position: ['bottomLeft'],
          current: artObj.page,
          pageSize: artObj.per_page,
          total: artObj.total_count,
          onChange: handleChange
        }} />
      </Card>
    </div>
  )
}